<template>
  <view class="userLayout" @touchmove.stop.prevent="handleTouchMove" @touchend="handleTouchEnd">
    <view class="back iconfont  icon-fenxiang" :style="statusBarHeight" @click="back">
    </view>
    <view class="img">
      <image :src="userData.img" mode="widthFix" :style="imageScale" class="image_" />
    </view>
    <view class="content" :style="contentTop">
      <view class="header">
        <view class="avatar">
          <image @load="hideLoading" @click="avatarPre" :src="userData.img" mode="widthFix" />
        </view>
        <view class="username-id">
          <view class="friendnickname">{{ remark ? remark : userData.nickname }}</view>
          <view class="username">
            <view class="tip">昵称:</view>
            {{ userData.nickname }}
          </view>
          <view class="userid">
            <view class="tip">ID:</view>
            {{ userData.userId }}
          </view>
        </view>
      </view>
      <view class="info" @click="openInfo">
        <view>详细信息</view>
        <view class=" iconfont icon-fenxiang"></view>
      </view>
      <view class="introduction">
        <view class="title">个人简介</view>
        <view class="text">{{ userData.introduce?.length > 0 ? userData.introduce : '这个人很奇怪,什么都没有写' }}</view>
      </view>
    </view>
    <view class="footer">
      <view class="button" @click="sendMsg">{{ btnText }}</view>
    </view>
  </view>
</template>

<script setup>
import gsap from 'gsap';
import { ref, getCurrentInstance, nextTick, reactive } from "vue"
import { getStatusBarHeight } from "../../utils/common.js"
import { onLoad, onReady, onShow } from '@dcloudio/uni-app';
import { reqTargetUser, reqRelation } from "../../api/user.js"
import { useUserStore } from "../../store/modules/user.js"
import { FG } from '../../api/req.js'
const { proxy } = getCurrentInstance();

let user = useUserStore()
let targetID = 0
let friendStatus = 0
let remark = ''
let userData = reactive({})
let btnText = ref("发送消息")

const statusBarHeight = `top:${getStatusBarHeight() + 10}px;`

let startY = 0;
let endY = 0;
let startX = 0
let endX = 0;

let contentTop = ref("top:20%;")
// #ifdef H5
let imageScale = ref('transform: scale(1);')
// #endif
// #ifdef MP-WEIXIN
let imageScale = ref('transform: scale(1);height: 100%;')
let imageHeight = 0
// #endif
let animEndflag = true   // 动画结束标志
let status = {
  top: 20,                 // 顶部距离
  scale: 1,                // 缩放比例
  topDiff: 0.15,           // 顶部距离变化量
  scaleDiff: 0.002,        // 缩放比例变化量
  scaleMax: 1.4,           // 最大缩放比例
  topMax: 60,              // 最大顶部距离
  topConst: 20,            // 顶部距离原始值
  scaleConst: 1,           // 缩放比例原始值
  scaleChangeStart: 25,    // 顶部距离变化量开始
  duration: 0.3            // 动画持续时间
}

function openInfo() {
  uni.navigateTo({
    url: `/pages/info/info?id=${targetID}`
  })
}

function handleTouchMove(event) {
  if (!animEndflag) {
    return;
  }
  // 记录当前触摸的X和Y坐标
  endX = event.changedTouches[0].clientX;
  endY = event.changedTouches[0].clientY;

  // 计算滑动的距离
  const deltaX = Math.abs(endX - startX);
  const deltaY = Math.abs(endY - startY);

  // 判断滑动方向
  if (deltaX > deltaY) {
    // 横向滑动
    return
  } else if (deltaY > deltaX) {
    // 垂直滑动
    if (endY < startY) {
      // 向上滑动
      status.top = status.top - status.topDiff
      status.top < 0 ? status.top = 0 : status.top = status.top
      if (status.top > status.scaleChangeStart && status.top <= status.topMax) {
        status.scale = status.scale - status.scaleDiff
        status.scale < status.scaleConst ? status.scale = status.scaleConst : status.scale = status.scale
      } else {
        status.scale = status.scaleConst
      }
      contentTop.value = `top:${status.top}%;`
      // #ifdef MP-WEIXIN
      imageScale.value = `transform: scale(${status.scale}); height:${imageHeight}px;`
      // #endif
      // #ifdef H5
      imageScale.value = `transform: scale(${status.scale});`
      // #endif
    } else if (endY > startY) {
      // 向下滑动
      status.top = status.top + status.topDiff
      status.top > status.topMax ? status.top = status.topMax : status.top = status.top
      if (status.top > status.scaleChangeStart && status.top <= status.topMax) {
        status.scale = status.scale + status.scaleDiff
        status.scale > status.scaleMax ? status.scale = status.scaleMax : status.scale = status.scale
      } else {
        status.scale = status.scaleConst
      }
      contentTop.value = `top:${status.top}%;`
      // #ifdef MP-WEIXIN
      imageScale.value = `transform: scale(${status.scale}); height:${imageHeight}px;`
      // #endif
      // #ifdef H5
      imageScale.value = `transform: scale(${status.scale});`
      // #endif
    }
  }
  startX = event.changedTouches[0].clientX;
  startY = event.changedTouches[0].clientY;
}

function handleTouchEnd(event) {
  animEndflag = false
  gsap.to(status, {
    top: status.topConst, // 目标数字
    scale: status.scaleConst,
    duration: status.duration, // 动画持续时间
    roundProps: "value",    // 确保数字四舍五入
    ease: "power2.out", // 动画缓动效果
    onUpdate: function () {
      // 在每一帧更新时执行的回调函数
      // 这里可以更新DOM元素或其他逻辑
      contentTop.value = `top:${status.top}%;`
      // #ifdef MP-WEIXIN
      imageScale.value = `transform: scale(${status.scale}); height:${imageHeight}px;`
      // #endif
      // #ifdef H5
      imageScale.value = `transform: scale(${status.scale});`
      // #endif
    },
    onComplete: function () {
      // 动画完成时的回调函数
      animEndflag = true
    },
  });
}
// #ifdef MP-WEIXIN
//获取图片区域的高度
function observeElementHeight() {
  // 创建选择器查询对象
  const query = uni.createSelectorQuery().in(proxy);

  // 选择需要监听高度变化的元素，假设这里有一个id为elementId的元素
  query.select('.image_')
    .boundingClientRect(data => {
      // data 包含了元素的布局信息，如 height, width 等
      console.log(data.height);
      imageHeight = data.height
      if (!imageHeight) {
        setTimeout(() => {
          observeElementHeight()
        }, 100);
      }
      // 在这里处理高度变化的逻辑
    })
    .exec();
}
onReady(() => {
  setTimeout(() => {
    observeElementHeight()
  }, 150);
})
// #endif
function avatarPre() {
  uni.previewImage({
    urls: [userData.img],
  })
}
function hideLoading() {
  nextTick(() => {
    uni.hideLoading()
  })
}

onLoad(async (param) => {
  console.log(26);
  uni.showLoading({
    mask: true,
  })
  targetID = param.userId

  if (!user.user) {
    return uni.switchTab({
      url: '/pages/chatList/chatList'
    })
  }
  friendStatus = +param.friendStatus
  if (param.remark) {
    remark = param.remark || ''
  }
})

onShow(async () => {

  try {
    console.log(27);
    let res = await reqTargetUser(targetID)
    if (res.status === 200) {
      for (let key in res.data) {
        userData[key] = res.data[key]
      }
    }
    userData.img = `${FG.baseUrl}/static/${userData.img}`
    if (!friendStatus) {
      res = await reqRelation({ uid: user.user._id, fid: userData._id })
      if (res.status >= 200 && res.status < 219) {
        friendStatus = +res.status
      }
    }
  } catch (err) {
    console.log(err);
    console.log("获取用户信息失败");
    uni.hideLoading()
  }

  switch (friendStatus) {
    case 200:
      btnText.value = "发送消息"
      break
    case 211:
      btnText.value = "等待对方同意"
      break
    case 213:
      btnText.value = "再次申请"
      break
    case 214:
      btnText.value = "禁止申请"
      break
    case 215:
      btnText.value = "对方已申请"
      break
    case 216:
      btnText.value = "已拒绝"
      break
    case 217:
      btnText.value = "已禁止申请"
      break
    default:
      btnText.value = "添加好友"
  }
})

function sendMsg() {
  switch (friendStatus) {
    case 200:
      uni.navigateTo({ url: `/pages/chat/chat?my=${user.user._id}&target=${userData._id}` })
      break
    case 215:
      uni.navigateTo({ url: '/pages/friendRequest/friendRequest' })
      break
    case 218:
      uni.navigateTo({ url: `/pages/addFriend/addFriend?userId=${userData.userId}` })
      break
  }
}

function back() {
  uni.navigateBack(1)
}
</script>

<style lang="scss" scoped>
.userLayout {
  width: 100%;
  height: 100vh;
  position: relative;

  .back {
    position: fixed;
    top: 0;
    font-size: 40rpx;
    left: 20rpx;
    z-index: 999;

  }

  .back.icon-fenxiang {
    mix-blend-mode: difference;
    text-transform: uppercase;
    color: #fff;
  }

  .img {
    width: 100%;

    image {
      width: 100%;
    }
  }

  .content {
    width: 100%;
    min-height: 80vh;
    position: absolute;
    border-radius: 5% 5% 0 0;
    background-color: #fff;

    .header {
      margin-top: 10rpx;
      width: 100%;
      height: 160rpx;
      padding: 0 20rpx;
      display: flex;

      .avatar {
        margin-right: 20rpx;

        image {
          width: 160rpx;
          border-radius: 50%;
        }
      }

      .username-id {
        display: flex;
        flex-direction: column;
        justify-content: space-around;

        .friendnickname {
          font-size: 30rpx;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          /* 限制在3行 */
          overflow: hidden;
        }

        .username,
        .userid {
          font-size: 24rpx;
          display: flex;
          align-items: center;
          color: #999;

          .tip {
            margin-right: 10rpx;
            font-size: 24rpx;

          }
        }
      }
    }

    .info {
      display: flex;
      height: 80rpx;
      justify-content: space-between;
      padding: 0 20rpx;
      align-items: center;
      margin: 20rpx 0;

      &:active {
        background-color: #f5f5f5;
      }

      .icon-fenxiang {
        transform: rotate(180deg);
      }
    }

    .introduction {
      width: 100%;
      padding: 0 20rpx;
      margin: 20rpx 0;

      .title {
        margin-bottom: 20rpx;
      }

      .text {
        border-radius: 5%;
        background-color: #eeeeee70;
        padding: 10rpx;
        min-height: 30vh;
        max-height: 50vh;
        color: #666;
        font-size: 30rpx;
      }
    }
  }

  .footer {
    width: 100%;
    height: 140rpx;
    position: fixed;
    bottom: calc(env(safe-area-inset-bottom) + 40rpx);
    background-color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;

    .button {
      width: 70%;
      height: 60%;
      background-color: #37b5e7;
      border-radius: 10rpx;
      text-align: center;
      line-height: calc(140rpx * 0.6);
      color: #fffc;
    }
  }
}
</style>